import React from "react";
import { CollapsibleItem as CollapsibleItemType } from "../types";

interface CollapsibleItemProps {
  item: CollapsibleItemType;
  onToggle: (id: string) => void;
  searchQuery: string;
  isHighlighted: boolean;
  onItemClick: (id: string) => void;
}

const CollapsibleItem: React.FC<CollapsibleItemProps> = ({
  item,
  onToggle,
  searchQuery,
  isHighlighted,
  onItemClick
}) => {
  const highlightText = (text: string, query: string) => {
    if (!query) return text;
    
    const regex = new RegExp(`(${query})`, 'gi');
    const parts = text.split(regex);
    
    return parts.map((part, index) => 
      regex.test(part) ? (
        <mark key={index} className="highlight">
          {part}
        </mark>
      ) : part
    );
  };

  const handleToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    onToggle(item.id);
  };

  const handleItemClick = () => {
    onItemClick(item.id);
  };

  return (
    <div 
      className={`collapsible-item ${isHighlighted ? 'highlighted' : ''}`}
      onClick={handleItemClick}
    >
      <div className="item-header">
        <button 
          className="toggle-button"
          onClick={handleToggle}
          aria-expanded={item.isExpanded}
        >
          {item.isExpanded ? '▼' : '▶'}
        </button>
        <h3 className="item-title">
          {highlightText(item.title, searchQuery)}
        </h3>
      </div>
      
      {item.isExpanded && (
        <div className="item-content">
          <p>{highlightText(item.content, searchQuery)}</p>
        </div>
      )}
    </div>
  );
};

export default CollapsibleItem;
